<?php

namespace app\admin\controller\qingdongwms\stock;


use addons\qingdongwms\model\PurchaseProduct;
use addons\qingdongwms\model\ProductPart;
use addons\qingdongwms\model\Product;

use addons\qingdongwms\model\Staff;
use addons\qingdongwms\model\Purchase;
use app\admin\controller\qingdongwms\Base;
use addons\qingdongwms\model\Supplier;
use addons\qingdongwms\model\ReturnedProduct;

use think\Db;
use think\Exception;


/**
 * 退货单
 * @icon fa fa-sign-in
 */
class Returned extends Base
{
    protected $relationSearch = true;
    /**
     * @var \addons\qingdongwms\model\Returned
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \addons\qingdongwms\model\Returned;
    }


    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres['owner_staff_id'] = array('in', Staff::getMyStaffIds());
            $list = $this->model->with(['supplier'])->where($where)
                ->where($wheres)->order($sort, $order)->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {

                $params = $this->preExcludeFields($params);

                if (isset($params['num'])) {
                    if (empty($params['num'])) {
                        $params['num'] = $this->model::getNum();
                    }
                    $instock = $this->model::where(['num' => $params['num']])->find();
                    if ($instock) {
                        $this->error('退货单编号已存在');
                    }
                } else {
                    $params['num'] = $this->model::getNum();
                }

                Db::startTrans();
                try {
                    if ($params['product']) {
                        $params['product'] = json_decode($params['product'], true);
                    }
                    $result = $this->model::createReturned($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $purchase = Purchase::where([])->select();
        $this->assign('purchase', $purchase);

        //供应商
        $supplier = Supplier::where(['status'=>1])->order('sort desc')->select();
        $this->assign('supplier', $supplier);
        $this->view->assign('num', $this->model::getNum());
        return $this->view->fetch();
    }


    /**
     * 修改
     * @param null $ids
     * @return string
     */
    public function edit($ids = null)
    {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $params = $this->request->post('row/a');
            $params = $this->preExcludeFields($params);


            Db::startTrans();
            try {
                if ($params['product']) {
                    $params['product'] = json_decode($params['product'], true);
                }

                $params['id'] = $ids;
                $result = $this->model::updateReturned($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('修改成功');
        }
        $row = $this->model->where($map)->find();
        $row = $row->toArray();

        $product=ReturnedProduct::where(['returned_id'=>$ids])->select();
        foreach($product as $k=>$v){
            $product[$k]['product_name'] = Product::where(['id'=>$v['product_id']])->value('name');
        }
        $row['product']=json_encode($product,true);
        //供应商
        $supplier = Supplier::where(['status'=>1])->order('sort desc')->select();
        $purchase = Purchase::where([])->select();
        $this->assign('purchase', $purchase);
        $this->assign('supplier', $supplier);
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }


    /**
     * 详情
     * @param null $ids
     * @return string
     */
    public function detail($ids = null)
    {
        $row = $this->model->where(['id' => $ids])->with([
            'ownerStaff'
        ])->find();
        if (empty($row)) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $row['supplier'] = Supplier::where(['id'=>$row['supplier_id']])->value('name');
        $row['purchase'] = Purchase::where(['id'=>$row['purchase_id']])->value('num');
        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $this->assignconfig("idinfo", ['id' => $ids]);
        return $this->view->fetch();
    }

    /**
     * 获取产品
     * @return \think\response\Json
     */
    public function get_product()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $countrys = Product::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品配置
     * @return \think\response\Json
     */
    public function get_product_part()
    {
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = $keyValue;
        }
        $name = input('name');
        if (!empty($name)) {
            $where['name'] = ['like', '%' . $name . '%'];
        }
        $countrys = ProductPart::where($where)->field('id,name')->order('id desc')->select();
        return json(['list' => $countrys, 'total' => count($countrys)]);
    }

    /**
     * 获取产品价格
     */
    public function get_product_price()
    {
        $id = input('id', 0);
        $product = Product::where(['id' => $id])->with(['goods'])->find();
        if(empty($product)){
            $this->error('参数错误');
        }
        $this->success('请求成功', '',$product);
    }

    /**
     * 获取产品明细
     */
    public function get_instock_product(){
        $returned_id=input('returned_id',0,'intval');
        if(empty($returned_id)){
            $this->error('参数不能为空');
        }
        $products=ReturnedProduct::where(['returned_id'=>$returned_id])->with(['product'])->select();

        return json(['rows' =>$products, 'total' => count($products)]);
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $map['id'] = array('in', $ids);
        $result = $this->model->destroy($map);
        if (!$result) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
}
